<!--
 * @Description: 堂食菜单
 * @Author: wrysunny
 * @Date: 2024-11-22 09:34:40
 * @LastEditor: wrysunny
 * @LastEditTime: 2024-12-11 11:40:14
-->
<template>
	<view class="w-full min-h-[100vh] bg-background">
		<view class="bg-white">
			<view :style="`height:${statusTop}px`"></view>
			<view class="flex items-center px-[24rpx] h-[80rpx]">
				<view class="text-gray px-[24rpx] h-[60rpx] flex items-center justify-center bg-white rounded-full mr-[24rpx] shadowX" @click="toGroupBuy">
					<up-image :src="coffice" width="36rpx" height="36rpx"></up-image>
					<view class="text-[24rpx] ml-[8rpx]">拼团</view>
				</view>
				<!-- #ifndef MP-WEIXIN -->
				<view class="flex px-[24rpx] h-[60rpx] items-center bg-white rounded-full shadowX flex-1">
					<up-icon name="search" color="#999" size="20"></up-icon>
					<input class="leading-[1] text-[24rpx]" type="text" v-model="keyword" placeholder="请输入商品名" @blur="getGoodsByMenu" />
				</view>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<view class="flex px-[24rpx] h-[60rpx] items-center bg-white rounded-full shadowX">
					<up-icon name="search" color="#999" size="20"></up-icon>
					<input class="leading-[1] text-[24rpx]" type="text" v-model="keyword" placeholder="请输入商品名" @blur="getGoodsByMenu" />
				</view>
				<!-- #endif -->
			</view>
		</view>
		<view class="px-[32rpx] h-[104rpx] bg-white flex items-center justify-between">
			<view class="flex items-center">
				<up-image radius="16rpx" :src="$setBaseUrl(currentShop.pic)" width="64rpx" height="64rpx"></up-image>
				<view class="text-[30rpx] font-bold ml-[12rpx]">{{ currentShop.name }}</view>
			</view>
			<view class="text-[24rpx] text-second" @click="toShopList">切换店铺&gt;</view>
			<!-- <up-swiper :list="[banner, banner, banner]" height="160rpx" indicatorActiveColor="#8C4F3D" indicatorInactiveColor="#C39A71" indicator indicatorMode="dot"></up-swiper> -->
		</view>
		<view class="grid grid-cols-[172rpx,1fr] mt-[24rpx]">
			<scroll-view :scroll-y="true" class="class_list" :style="`height:calc(100vh - ${statusTop}px - 210rpx - var(--window-bottom))`" :scroll-into-view="'into' + current">
				<view
					class="class_list_item"
					:class="{
						active: index == current
					}"
					v-for="(item, index) in list"
					:key="item.appGoodCategory.id"
					@click="changeTab(index)"
					:id="'into' + index"
				>
					{{ item.categoryName }}
				</view>
			</scroll-view>
			<scroll-view
				:scroll-y="true"
				:scroll-into-view="'into' + current"
				class="px-[20rpx] box-border scroll"
				:style="`height:calc(100vh - ${statusTop}px - 210rpx - var(--window-bottom))`"
				scroll-with-animation
				@scroll="scroll"
				:scroll-top="scrollTop"
				@touchstart="isScroll = true"
			>
				<view class="bg-white w-full rounded-[16rpx]">
					<template v-for="(item, index) in list" :key="item.appGoodCategory.id">
						<view class="scroll_item">
							<view class="flex justify-between items-center px-[24rpx] py-[20rpx]">
								<view class="">
									<view class="font-bold text-[30rpx]">{{ item.categoryName }}</view>
									<view class="text-[20rpx] text-gray">{{ item.appGoodCategory?.brief || '' }}</view>
								</view>
								<!-- <view class="text-[26rpx] text-gray flex items-center">
									价格
								</view> -->
							</view>
							<template v-if="item.appGoods.length">
								<view class="p-[20rpx] flex" v-for="it in item.appGoods" :key="it.id" @click="toDetail(it.id)">
									<!-- <up-image :src="$setBaseUrl(it.pic)" width="128rpx" height="128rpx"></up-image> -->
									<view class="w-[128rpx] h-[128rpx]">
										<up-lazy-load :image="$setBaseUrl(it.pic)" width="128rpx" height="128rpx"></up-lazy-load>
									</view>
									<view class="flex flex-col justify-between ml-[16rpx]">
										<view class="">
											<view class="text-black text-[26rpx]">{{ it.name }}</view>
											<view class="text-gray text-[22rpx]">{{ it.brief }}</view>
										</view>
										<view class="text-[28rpx]">
											<text class="text-[#FF4D1B]">¥{{ it.price }}</text>
											<text class="text-gray line-through ml-[8rpx]">¥{{ it.demoPrice }}</text>
										</view>
									</view>
									<view class="ml-auto flex items-end">
										<up-image :src="add" width="32rpx" height="32rpx"></up-image>
									</view>
								</view>
							</template>
							<up-empty mode="data" marginTop="0" text="查询结果为空" v-else></up-empty>
						</view>
					</template>
				</view>
			</scroll-view>
		</view>
		<ShoppingBag
			:isPackUp="isPackUp"
			@packUp="isPackUp = !isPackUp"
			:cartList="cartList"
			@cartChange="updateCartFn({ list: cartList })"
			@deleteCart="deleteCartFn({ list: [{ id: $event }] })"
			@clearCart="deleteCartFn({ list: cartList })"
			@account="toCheckout"
		></ShoppingBag>
	</view>
</template>

<script setup>
import coffice from '@/static/coffice.png';
import add from '@/static/add.png';
import { onLoad, onReady, onShow } from '@dcloudio/uni-app';
import { nextTick, ref } from 'vue';
import { getGoodsListByMenu } from '@/config/api/goods';
import { debounce } from '@/uni_modules/uview-plus';
import useCart from '@/hooks/useCart';
import useShop from '@/hooks/useShop';
const statusTop = ref(0); //状态栏高度
const isPackUp = ref(false); //是否收起购物车
onLoad(() => {
	statusTop.value = uni.getWindowInfo().statusBarHeight;
});
onReady(() => {
	// nextTick(() => {
	// 	setTimeout(async () => {
	// 		await initScrollView();
	// 	}, 500);
	// });
});
onShow(async () => {
	await getCurrentShop();
	await getGoodsByMenu();

	if (uni.getStorageSync('token')) {
		getCartListFn();
	}
});
const { list, getGoodsByMenu, keyword } = useGoodsByMenu(); // 商品列表

const { current, changeTab, scroll, initScrollView, getElementTop, isScroll, isGetTop, scrollTop } = useSort(); // 分类列表

const { cartList, getCartListFn, updateCartFn, deleteCartFn } = useCart(); // 购物车

const { getCurrentShop, currentShop } = useShop();
//分类列表
function useSort() {
	const current = ref(0); // 当前tab
	const isScroll = ref(false); // 很关键
	const isGetTop = ref(true);
	const scrollTop = ref(0);
	const scrollTopSize = ref(0);
	const scrollHeight = ref(0);
	const topArr = ref([]);
	const changeTab = (e) => {
		current.value = e;
		isScroll.value = false;
		scrollTop.value = topArr.value[e];
	};
	const scroll = (e) => {
		if (!isScroll.value) {
			return;
		}
		debounce(() => {
			const index = findLastIndex(topArr.value, (item) => {
				return e.detail.scrollTop > item - 10;
			});
			console.log(index);
			current.value = index < 0 ? 0 : index;
		}, 100);
	};
	/* 初始化滚动区域 */
	const initScrollView = () => {
		return new Promise((resolve, reject) => {
			let view = uni.createSelectorQuery().select('.scroll');
			view.boundingClientRect((res) => {
				scrollTopSize.value = res.top;
				scrollHeight.value = res.height;
				nextTick(() => {
					resolve();
				});
			}).exec();
		});
	};
	/* 获取元素顶部信息 */
	const getElementTop = () => {
		new Promise((resolve, reject) => {
			let view = uni.createSelectorQuery().selectAll('.scroll_item');
			view.boundingClientRect((data) => {
				resolve(data);
			}).exec();
		}).then((res) => {
			if (isGetTop.value) {
				let arr = res.map((item) => {
					return item.top - scrollTopSize.value; /* 减去滚动容器距离顶部的距离 */
				});
				topArr.value = arr;
				isGetTop.value = false;
			}
		});
	};
	const findLastIndex = (array, predicate) => {
		for (let i = array.length - 1; i >= 0; i--) {
			if (predicate(array[i], i, array)) {
				return i;
			}
		}
		return -1;
	};
	return {
		current,
		changeTab,
		scroll,
		isScroll,
		isGetTop,
		initScrollView,
		getElementTop,
		scrollTop
	};
}

//商品列表
function useGoodsByMenu() {
	const keyword = ref(''); //搜索关键词
	const list = ref([]);
	const getGoodsByMenu = async () => {
		try {
			const res = await getGoodsListByMenu({
				sortString: 'id', // price
				searchKey: keyword.value
			});
			list.value = res.data;
			nextTick(() => {
				getElementTop();
				initScrollView();
			});
		} catch (e) {
			//TODO handle the exception
		}
	};
	return {
		keyword,
		list,
		getGoodsByMenu
	};
}
const toDetail = (id) => {
	uni.navigateTo({
		url: `/pages/drinkDetail/drinkDetail?id=${id}`
	});
};

const toGroupBuy = () => {
	uni.navigateTo({
		url: '/pages/groupBuy/groupBuy'
	});
};

const toCheckout = () => {
	uni.navigateTo({
		url: '/pages/checkout/checkout'
	});
};

const toShopList = () => {
	uni.navigateTo({
		url: '/pages/shopList/shopList'
	});
};
</script>

<style lang="scss" scoped>
.shadowX {
	box-shadow: 0rpx 0rpx 8rpx 2rpx rgba(161, 84, 36, 0.16);
}
.class_list {
	@apply text-[26rpx] text-center;
	&_item {
		@apply px-[20rpx] py-[18rpx] bg-opacity-0 transition-all rounded-e-full bg-third text-black mb-[24rpx] last:mb-0;
	}
	.active {
		@apply bg-opacity-100 font-bold text-second;
	}
}
</style>
